<?php
namespace app\api\service;

use app\BaseController;
use app\common\model\User;
use app\common\model\Recharge;
use app\common\model\Detailed;
use app\common\model\UserAmount;
use app\common\model\PaySettings;
use app\common\service\CommonWechatPayService;
use EasyWeChat\Factory;
use app\Response;
use think\facade\Db;
use think\facade\Cache;
use think\facade\Config;

class RechargeService
{
    public static function wxRechargBalanceService($user_id,$data){
        $userInfo = User::userInfo(["uid"=>$user_id]);
        if(empty($userInfo)){
            return Response::wrapError('非法请求',-200);
        }
        if($userInfo['type'] != 23){
            return Response::wrapError('账户非达人用户',-200);
        }
        if($userInfo['enable'] == 0){
            return Response::wrapError('此账户已被禁用,如有疑问请联系客服人员',-200);
        }
        if(empty($userInfo["open_id"])){
            return Response::wrapError("请先绑定微信!");
        }
        if(Cache::has("userAmount".$user_id)&&!empty(Cache::get("userAmount".$user_id))&&Cache::get("userAmount".$user_id)>15){
            return Response::wrapError('系统结算中请稍后再试!');
        }
        $time = time();

        //订单编号生成
        $out_trade_no = date('YmdHis',time()) .rand(10000,99999);
//        $data['amountMoney'] = 0.03;

        //套餐购买记录生成
        $res = self::rechargeAdd($user_id,['order_no'=>$out_trade_no,'pay_channel'=>'wx_pub','pay_amt'=>sprintf("%.2f",$data['amountMoney'])],'');
        if($res){
            $info = CommonWechatPayService::miniPayData($user_id,$userInfo["open_id"],$data['amountMoney'],$out_trade_no);
            Cache::set("userAmount".$user_id,20,30);
            if(!empty($info)){
                return Response::wrapData($info);
            }else{
                return Response::wrapData("操作失败");
            }
        }else{
            return Response::wrapData("操作失败");
        }
    }

    //充值记录记录
    public static function rechargeAdd($uid,$payment_params,$voucher){
        $data = [
            'uid' => $uid,
            'no_order' => $payment_params['order_no'],
            'payment_type' => ($payment_params['pay_channel'] == 'alipay_qr')?5:6,
            'amount_money' => $payment_params['pay_amt'],
            'voucher' => $voucher,
            'state' => 0,
            'addtime' => time(),
            'remarks' => '订单提交成功',
        ];
        if($payment_params['pay_channel'] == 'wx_pub'){
            $data["payment_type"] = 3;
        }
        return Recharge::rechargeAdd($data);
    }



    /*** 获取充值渠道开启接口
     * @return array
     */
    public static function paySettingsService(){
        $info = PaySettings::paySettingsView(['state'=>1]);
        return ['code' => 1, 'msg' => lang(''), 'data' => $info, 'count' => ''];
    }






}